﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Google.GData.Calendar;
using Google.GData.Client;
using Google.GData.Extensions;

namespace GCalPlugin
{
    public class GCalJournal
    {
        private CalendarService service;
        private Uri postUri;
        const string applicationName = "TS_GCalPlugin";

        public GCalJournal(string username, string password,Uri feedUri)
        {
            service = new CalendarService(applicationName);
            // Set your credentials:
            service.setUserCredentials(username, password);
            postUri = feedUri;
        }
        public Dictionary<string, Uri> LoadFeeds()
        {
            try
            {
                var q = new CalendarQuery("http://www.google.com/calendar/feeds/default/owncalendars/full");
                var calendars = service.Query(q);
                var list = new Dictionary<string, Uri>();
                foreach (var calendar in calendars.Entries)
                {
                    string feedstring = calendar.Id.AbsoluteUri.Substring(63);
                    var uri = new Uri("https://www.google.com/calendar/feeds/" + feedstring + "/private/full");
                    list.Add(calendar.Title.Text, uri);
                }
                return list;
            }
            catch (Exception e)
            {
                //TODO: log
                return null;
            }
        }
        public void InsertNewEntry(DateTime start, DateTime end, string title, string description, string project)
        {
            EventEntry entry = new EventEntry();

            // Set the title and content of the entry.
            entry.Title.Text = title;
            entry.Content.Content = description;

            // Set a location for the event.
            Where eventLocation = new Where();
            eventLocation.ValueString = project;
            entry.Locations.Add(eventLocation);

            When eventTime = new When(start, end);
            entry.Times.Add(eventTime);

            // Send the request and receive the response:
            //TODO: insert a try in case Internet is down or we cannot connect to GCAL
            AtomEntry insertedEntry = service.Insert(postUri, entry);
        }
    }
}
